package logic

import (
	"context"
	"errors"
	"shoppingcart-srv/model/mysql"
	"shoppingcart-srv/model/redis"

	"shoppingcart-srv/internal/svc"
	"shoppingcart-srv/shoppingcart"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *shoppingcart.AddCartRequest) (*shoppingcart.AddCartResponse, error) {
	// todo: add your logic here and delete this line
	//g := mysql.Goods{
	//	Model: gorm.Model{ID: uint(in.GoodsId)},
	//}
	//err := g.FindID()
	//if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
	//	return nil, errors.New("查询商品信息失败")
	//}
	//商品库存是否充足(虚拟库存)
	stock, err := redis.GetGoodsStock(in.GoodsId)
	if err != nil {
		return nil, errors.New("redis获取商品库存失败")
	}
	if stock >= in.Quantity {
		return nil, errors.New("库存不足")
	}
	c := mysql.Cart{
		UserId:  in.UserId,
		GoodsId: in.GoodsId,
	}

	if c.Exist() { //商品已存在购物车
		c.Quantity += in.Quantity
		err = c.UpdateQuantity()
	} else { //添加到购物车
		c = mysql.Cart{
			UserId:     in.UserId,
			GoodsId:    in.GoodsId,
			GoodsPrice: in.GoodsPrice,
			Quantity:   in.Quantity,
			Checked:    1,
		}
		err = c.Add()
	}
	if err != nil {
		return nil, errors.New("添加商品失败")
	}
	err = redis.RemoveGoodStock(in.GoodsId, in.Quantity)
	if err != nil {
		return nil, err
	}
	return &shoppingcart.AddCartResponse{Success: true}, nil
}
